package com.zhsj.OkeHomeConsumption.ui.activity;

import android.app.Dialog;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.bar.TitleBar;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MenuDialog;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.MerchantTypeBean;
import com.zhsj.OkeHomeConsumption.empty.ShopListBean;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.FreshfruitPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.mvp.FreshfruitUIInterFace;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.SharedPreferanceUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * 商铺页面
 */

public class FreshfruitActivity extends MyActivity implements View.OnClickListener, FreshfruitUIInterFace {

    private RecyclerView rvList_freshfruit;
    private TitleBar tb_freshfruit_title;
    private TabLayout tab_freshfruit;
    private TextView bt_freshruit_one;
    private ImageView banner_image;
    private ArrayList<String> tabs;
    private ArrayList<MerchantTypeBean> mMerchantTypeLists = null;
    //    //tablayoutw位置
    //tablayoutw位置
    private ArrayList<MerchantTypeBean> mMerchantTypeTwoLists = null;
    private ArrayList<MerchantTypeBean> mMerchantTypeThreeLists = null;
    private List<String> datalist = null;//三级列表
    private int posion =-1;
    //店铺
    private List<ShopListBean> ShopList = null;
    private FreshfruitPresenter minePersonPresenter;
    private SharedPreferanceUtils mSharePreferanceUtils = null;
    /**
     * @Fields topurlArr : TODO banner部url标题集合
     */
    private LinkedHashMap<String, String> topUrlTitleArr = null;
    //图片集合
    private ArrayList<String> imageUrlList = null;
    private ArrayList<String> webUrlList = null;
    private ArrayList<Integer> imagemodle = null;
    private List<String> mBannerTitleLists = null;
    private int categoryLevel1Id = -1;//一级分类id

    private BGABanner bannerGuideContent;

    private int cityId = -1;
    private ShopAdapter shopAdapter;
    private int id;

    private int flage = -1;
    private  double userLongitude ;

    private double userLatitude;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_freshfruit;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_freshfruit_title;
    }

    @Override
    protected void initView() {

         userLongitude = Hawk.get("userLongitude");

         userLatitude = Hawk.get("userLatitude");
        minePersonPresenter = new FreshfruitPresenter(getActivity(), this);
        bannerGuideContent = findViewById(R.id.banner_guide_content);
        tb_freshfruit_title = findViewById(R.id.tb_freshfruit_title);
        tb_freshfruit_title.setOnClickListener(this);
        tab_freshfruit = findViewById(R.id.tab_freshfruit);
        tab_freshfruit.setOnClickListener(this);
        bt_freshruit_one = findViewById(R.id.bt_freshruit_one);
        bt_freshruit_one.setOnClickListener(this);
        banner_image = findViewById(R.id.banner_image);
        banner_image.setOnClickListener(this);
        rvList_freshfruit = findViewById(R.id.rvList_freshfruit);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        rvList_freshfruit.setLayoutManager(linearLayoutManager);
        tab_freshfruit.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                id = mMerchantTypeTwoLists.get(tab.getPosition()).getId();
                minePersonPresenter.ShopListPost(categoryLevel1Id + "",
                        id + "", 1, cityId,userLongitude,userLatitude);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }




    @Override
    protected void initData() {
        final Intent intent = getIntent();
        String titlename = intent.getStringExtra("titlename");
        tb_freshfruit_title.setTitle(titlename);
        mMerchantTypeLists = (ArrayList<MerchantTypeBean>) intent.getSerializableExtra("mMerchantTypeLists");
        mSharePreferanceUtils = new SharedPreferanceUtils(getActivity());
        posion =  intent.getIntExtra("position",0);
        if(mMerchantTypeLists.size()!=0&&mMerchantTypeLists!=null){
            categoryLevel1Id =  mMerchantTypeLists.get(posion).getId();
        }
        minePersonPresenter.MerchantTypeGet(mMerchantTypeLists.get(posion).getId()+"", mSharePreferanceUtils.getSelectCityId() + "");
        tabs = new ArrayList<>();
        cityId = Hawk.get(Constants.SHARED_PERFERENCE_SELECTCITYID,-1);
        if(cityId==-1){
            toast("请选择城市");
            return;
        }
        minePersonPresenter.IndexBannerGET(mMerchantTypeLists.get(posion).getBannerModule());
        bannerGuideContent.setDelegate(new BGABanner.Delegate<ImageView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, ImageView itemView, String model, int position) {
                startActivity(new Intent(getActivity(), WebActivity.class).putExtra("url", webUrlList.get(position)));
//                Toast.makeText(banner.getContext(), "点击了" + position, Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_freshruit_one:
                MenuDialog(datalist);
                break;
            case R.id.banner_image:
                Intent intent1 = new Intent(getActivity(), WebActivity.class).putExtra("url",
                        OkeHomeConsumptionApi.ELVDOU_BASEURL_H5 + "app/h5/platform/29.html");
                startActivity(intent1);
                break;

        }
    }

    /**
     *获取店铺列表
     */
    @Override
    public void ShopListPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                JSONArray jsonarr = jsonobj.optJSONArray("jsonObj");
                // 数据对接正常

                ShopList = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<ShopListBean>>() {
                        }.getType());
                shopAdapter = new ShopAdapter();
                rvList_freshfruit.setAdapter(shopAdapter);
                View view = LinearLayout.inflate(this, R.layout.shop_isnull, null);
                shopAdapter.setEmptyView(view);
//                if(ShopList.size()>0){
//                    minePersonPresenter.ShopListPost(categoryLevel1Id + "",
//                            id + "", 1, cityId);
//                }else{
//                    toast("正在招募中");
//                }


            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("ShopListPost", "获取店铺列表");
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // Do something
                         finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void MerchantTypeGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
                // 数据对接正常
                mMerchantTypeTwoLists = new Gson().fromJson(jsonarr.toString(), new
                        TypeToken<ArrayList<MerchantTypeBean>>() {
                        }.getType());
                for (int i = 0; i < mMerchantTypeTwoLists.size(); i++) {
                    tab_freshfruit.addTab(tab_freshfruit.newTab().setText(mMerchantTypeTwoLists.get(i).getName()));
                }
                if(mMerchantTypeTwoLists.size()!=0&&mMerchantTypeTwoLists!=null){
                    minePersonPresenter.ShopListPost(categoryLevel1Id+"",mMerchantTypeTwoLists.get(0).getId()+"",1,cityId,userLongitude,userLatitude);
                }

            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("MerchantTypeGet", "获取经营类型异常");
        }
    }

    /**
     * 获取三级分类
     * */
    @Override
    public void MerchantTypeThreeGet(String context) {
//        try {
//            JSONTokener jsonT = new JSONTokener(context);
//            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
//            String code = jsonOBJ.optString("code");
//            String message = jsonOBJ.optString("message");
//            if (code.equals("N000000")) {
//                JSONArray jsonarr = jsonOBJ.optJSONArray("data");
//                // 数据对接正常
//                mMerchantTypeThreeLists = new Gson().fromJson(jsonarr.toString(), new
//                        TypeToken<ArrayList<MerchantTypeBean>>() {
//                        }.getType());
//                datalist = new ArrayList<>();
//            } else if (code.equals(Constants.STATUSTOKENERROR)) {
//                // token过期
//                if (!message.equals("null")) {
//                    toast(message);
//                }
//            } else {
//                if (!message.equals("null")) {
//                    toast(message);
//                }
//            }
//        } catch (JSONException ex) {
//            Log.e("MerchantTypeThreeGet", "获取店铺三级分类异常");
//        }
    }
    @Override
    public void IndexBannerGET(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                // 首页Banner数据
                JSONArray optJSONArray = jsonOBJ.optJSONArray("data");
                topUrlTitleArr = new LinkedHashMap<String, String>();
                imageUrlList = new ArrayList<String>();
                webUrlList = new ArrayList<>();
                imagemodle = new ArrayList<>();
                mBannerTitleLists = new ArrayList<String>();
                // 首页数据
                for (int i = 0; i < optJSONArray.length(); i++) {
                    final JSONArray imgPathArray = optJSONArray.optJSONObject(i).optJSONArray("imgPath");
                    if (!imageUrlList.contains(imgPathArray.optString(0))) {
                        imageUrlList.add(imgPathArray.optString(0));
                    }
                    if (!topUrlTitleArr.containsKey(optJSONArray.optJSONObject(i).optString("title")) &&
                            !topUrlTitleArr.containsValue(optJSONArray.optJSONObject(i).optString("url"))) {
                        topUrlTitleArr.put(optJSONArray.optJSONObject(i).optString("title"),
                                optJSONArray.optJSONObject(i).optString("url"));
                        mBannerTitleLists.add(optJSONArray.optJSONObject(i).optString("title"));
                        imagemodle.add(optJSONArray.optJSONObject(i).optInt("module"));
                        webUrlList.add(optJSONArray.optJSONObject(i).optString("url"));
                    }

                }
                //设置图片集合
                bannerGuideContent.setAdapter(new BGABanner.Adapter<ImageView, String>() {
                    @Override
                    public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                        Glide.with(getActivity())
                                .load(model)
//                                .placeholder(R.drawable.homebanneryi)
                                .error(R.drawable.homebannerer)
                                .centerCrop()
                                .dontAnimate()
                                .into(itemView);
                    }
                });

                bannerGuideContent.setData(imageUrlList, mBannerTitleLists);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                }
            } else {
                if (!message.equals("null")) {
                }

            }
        } catch (Exception ex) {
            LogUtils.e("IndexFragemnt banner", "数据获取异常 ");
        }


    }

    private void MenuDialog( List<String> datalist){
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(datalist)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        bt_freshruit_one.setText(text);
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }


    public class ShopAdapter extends BaseQuickAdapter<ShopListBean, BaseViewHolder> {


        public ShopAdapter() {
            super(R.layout.fragment_fresh_item, ShopList);
        }

        @Override
        protected void convert(BaseViewHolder helper, final ShopListBean item) {
            helper.setText(R.id.factotyname, item.getShopName())
                    .setText(R.id.factotyplace, item.getDistricCountryName()+" | "+distanceFormat(item.getDistanceMeter()))
                    .setText(R.id.classify, item.getCategoryText())
                    .setText(R.id.factoryallplace, item.getAddress())
            .setOnClickListener(R.id.lin, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转首页推荐店铺详情
                    Intent intent = new Intent(getActivity(), RestaurantActivity.class);
                    intent.putExtra("itemid", item.getId());
                    startActivity(intent);
                }});
            ImageView imagev = helper.itemView.findViewById(R.id.image);
            Glide.with(getActivity()).load(item.getShopLogo()).placeholder(R.drawable.zhanweitu_bg).into(imagev);

        }
    }

    /**
     * 距离只保留两位小数
     * @param distance 以米为单位
     * @return
     */
    public static String distanceFormat(double distance) {
        String str;
        double value = distance;
        if (distance >= 1000) {
            value = value / 1000;
            str = "KM";
        } else {
            str = "M";
        }
        return value+str;
    }
}
